package com.flyoil.petromp.ui.fragment.fragment_statiscs;

import android.app.ActionBar;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cnpc.fyutils.ToastUtils;
import com.flyoil.petromp.Constant.ConstantNetworkCode;
import com.flyoil.petromp.R;
import com.flyoil.petromp.adapter.adapter_statics.ItemStaticSelectSupplierAdapter;
import com.flyoil.petromp.adapter.adapter_statics.ItemStaticSelectTypeAdapter;
import com.flyoil.petromp.apiservice.HttpModel;
import com.flyoil.petromp.apiservice.OnObserverRetrofitResetCallBack;
import com.flyoil.petromp.base.BaseEntity;
import com.flyoil.petromp.base.BaseFragment;
import com.flyoil.petromp.entity.entity_statics.StaticsDataEntity;
import com.flyoil.petromp.entity.entity_statics.StaticsDeptListEntity;
import com.flyoil.petromp.entity.entity_statics.StaticsSelectTypeEntity;
import com.flyoil.petromp.utils.BarChartUtils;
import com.flyoil.petromp.utils.Dialog.DialogHintUtil;
import com.flyoil.petromp.utils.Dialog.Dialog_util;
import com.flyoil.petromp.utils.HintConstants;
import com.flyoil.petromp.utils.LineChartUtils;
import com.flyoil.petromp.utils.MoccaPreferences;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by songzhiiyn on 2017/9/27.
 * 部门统计页面
 */

public class StatisticsDepartmentFragment extends BaseFragment {
    private GridView grid_time, grid_type;
    private ItemStaticSelectTypeAdapter adapter_time, adapter_type;
    private ItemStaticSelectSupplierAdapter itemStaticSelectSupplierAdapter;
    private List<StaticsSelectTypeEntity> timeEntitiess;
    private List<StaticsSelectTypeEntity> supplierEntitiess;
    private PopupWindow popupWindow;
    private LinearLayout line_select, line_money, line_number;
    private ImageView img_select;
    private TextView tv_money, tv_number;
    private View view_backgroud, view_money, view_number;
    private LinearLayout rela_chart;
    private String[] data_dimension = new String[]{"LAST_MONTH", "LAST_QUARTER", "LAST_YEAR"};
    private int[] data_color = new int[]{R.color.bardata1, R.color.bardata2, R.color.bardata3};
    private String dimension = data_dimension[0];
    private StringBuffer ids = new StringBuffer();
    private String type = "amount";//默认计划总金额
    private List<String> xAxisValue = new ArrayList<>();
    private ArrayList<IBarDataSet> dataSets = new ArrayList<>();
    private List<ILineDataSet> lineDataSets = new ArrayList<>();
    private int max = 3;


    @Override
    protected int getContentViewResId() {
        return R.layout.fragment_statics_department;
    }

    @Override
    protected void initViews() {
        super.initViews();
        grid_time = $(R.id.grid_statics_department_time);
        grid_type = $(R.id.grid_statics_department_select_type);
        line_select = $(R.id.line_statics_depart_select);
        img_select = $(R.id.img_statics_depart_select);
        view_backgroud = $(R.id.view_background);
        line_money = $(R.id.line_statics_depart_money);
        line_number = $(R.id.line_statics_depart_number);
        tv_money = $(R.id.tv_statics_depart_money);
        tv_number = $(R.id.tv_statics_depart_number);
        view_money = $(R.id.view_statics_depart_money);
        view_number = $(R.id.view_statics_depart_number);
        rela_chart = $(R.id.rela_statics_fragment_chart);
        adapter_time = new ItemStaticSelectTypeAdapter(mContext);
        adapter_type = new ItemStaticSelectTypeAdapter(mContext);
        grid_time.setAdapter(adapter_time);
        grid_type.setAdapter(adapter_type);
        httpModel = new HttpModel();
    }

    @Override
    protected void initdatas() {
        super.initdatas();
        timeEntitiess = new ArrayList<>();
        supplierEntitiess = new ArrayList<>();
        timeEntitiess.add(new StaticsSelectTypeEntity("最近一月", 0, true));
        timeEntitiess.add(new StaticsSelectTypeEntity("最近一季度", 1, false));
        timeEntitiess.add(new StaticsSelectTypeEntity("最近一年", 2, false));
        adapter_time.addDataBottom(timeEntitiess);
        getStatisticsConditionDeptList();
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        grid_time.setOnItemClickListener(onItemClickListener_time);
        line_select.setOnClickListener(onClickListener);
        view_backgroud.setOnClickListener(onClickListener);
        line_number.setOnClickListener(onClickListener);
        line_money.setOnClickListener(onClickListener);
    }

    /**
     * 设置折线图表的样式属性
     */
    private void setLineChart() {
        rela_chart.removeAllViews();
        LineChart mLineChart = new LineChart(mContext);
        mLineChart.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        rela_chart.addView(mLineChart);
        LineChartUtils.initChart(mLineChart, mContext, xAxisValue);
        LineChartUtils.notifyDataSetChanged(mLineChart, lineDataSets, true, xAxisValue.size());
    }

    /**
     * 设置柱状图表的样式属性
     */
    private void setBarChart() {
        rela_chart.removeAllViews();
        BarChart mBarChart = new BarChart(mContext);
        mBarChart.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        rela_chart.addView(mBarChart);
        BarChartUtils.initChart(mBarChart, mContext, xAxisValue);
        BarChartUtils.notifyDataSetChanged(mBarChart, dataSets, true, xAxisValue.size());
    }


    /**
     * 获取部门统计的数据
     */
    private void getStatisticsDeptList() {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("dimension", dimension);
        map.put("type", type);
        Dialog_util.start_NetworkRequests_diolog(mContext);
        httpModel.getStatisticsDeptList(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                Dialog_util.close_NetworkRequests_diolog();
                StaticsDataEntity entity = null;
                if (model instanceof StaticsDataEntity) {
                    entity = (StaticsDataEntity) model;
                }
                if (entity != null && entity.getCode() == ConstantNetworkCode.SuccedCode && entity.getData().getSeries() != null) {
                    if (entity.getData().getTimeLine() != null) {
                        xAxisValue.clear();
                        xAxisValue.addAll(entity.getData().getTimeLine());
                    }
                    if (entity.getData().getSeries().size() == 1) {
                        setLineChartData(entity);
                        setLineChart();
                    }
                    if (entity.getData().getSeries().size() > 1) {
                        setBarChartData(entity);
                        setBarChart();
                    }
                }else{
                    ToastUtils.show_toast(model.getMessage());
                }
            }

            @Override
            public void onFailure(String msg) {
                Dialog_util.close_NetworkRequests_diolog();
            }
        });
    }

    /**
     * 初始化折线图的数据
     *
     * @return
     */
    private List<ILineDataSet> setLineChartData(StaticsDataEntity entity) {
        lineDataSets.clear();
        //折线1
        List<Entry> values = new ArrayList<>();
        for (int i = 0; i < entity.getData().getSeries().get(0).getData().size(); i++) {
            values.add(new Entry(i, entity.getData().getSeries().get(0).getData().get(i)));
//            int y = new Random().nextInt(max) % (max - 0 + 1) + 0;
//            values.add(new Entry(i, y));

        }
        LineDataSet mLineDataSet = new LineDataSet(values, entity.getData().getSeries().get(0).getLabel());
        // 设置曲线颜色
        mLineDataSet.setColor(mContext.getResources().getColor(R.color.statics_line_color));
        // 设置平滑曲线
        mLineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        // 不显示坐标点的小圆点
        mLineDataSet.setDrawCircles(true);
        // 不显示坐标点的数据
        mLineDataSet.setDrawValues(true);
        // 不显示定位线
        mLineDataSet.setHighlightEnabled(false);
        //设置范围的颜色
        mLineDataSet.setDrawFilled(true);
        mLineDataSet.setFillColor(mContext.getResources().getColor(R.color.statics_line_fill_color));
        lineDataSets.add(mLineDataSet);
        return lineDataSets;
    }

    /**
     * 初始化柱状图的数据
     *
     * @param entity
     * @return
     */
    private ArrayList<IBarDataSet> setBarChartData(StaticsDataEntity entity) {
        dataSets.clear();
        for (int i = 0; i < entity.getData().getSeries().size(); i++) {
            List<BarEntry> barEntries = new ArrayList<>();
            for (int j = 0; j < entity.getData().getSeries().get(i).getData().size(); j++) {
                barEntries.add(new BarEntry(j, entity.getData().getSeries().get(i).getData().get(j)));
//                int y = new Random().nextInt(max) % (max - 0 + 1) + 0;
//                barEntries.add(new BarEntry(j, y));
            }
            BarDataSet iBarDataSet = new BarDataSet(barEntries, entity.getData().getSeries().get(i).getLabel());
            iBarDataSet.setColors(getResources().getColor(data_color[i]));
            iBarDataSet.setDrawValues(false);//柱状图上不显示数据
            dataSets.add(iBarDataSet);
        }
        return dataSets;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.line_statics_depart_select://弹出选择框
                    showSelectTypePopup();
                    break;
                case R.id.view_background://取消popup
                    popupWindow.dismiss();
                    break;
                case R.id.tv_popup_statics_supplier_confirm://确定选择的条件
                    if (getSelectTypeEntities().size() > 3) {
                        ToastUtils.show_toast(HintConstants.STATICS_SELECT_SIZE);
                        return;
                    }
                    if (getSelectTypeEntities().size() == 0) {
                        ToastUtils.show_toast(HintConstants.STATICS_SELECT_MIN_SIZE);
                        return;
                    }
                    adapter_type.setdate(getSelectTypeEntities());
                    popupWindow.dismiss();
                    searchStatisicsData();
                    break;

                case R.id.line_statics_depart_money://查询金额
                    setSearchTypeStatus(0);
                    max = 6000;
                    break;
                case R.id.line_statics_depart_number://查询数量
                    setSearchTypeStatus(1);
                    max = 2;
                    break;
            }
        }
    };

    /**
     * 搜索数据
     */
    private void searchStatisicsData() {
        if (adapter_type.getData().size() == 0) {
            ToastUtils.show_toast("请先选择部门在进行统计");
            return;
        }
        ids.delete(0, ids.length());
        for (int i = 0; i < adapter_type.getData().size(); i++) {
            if (i > 0) {
                ids.append("," + adapter_type.getData().get(i).getId());
            } else {
                ids.append(adapter_type.getData().get(i).getId());
            }
        }
        getStatisticsDeptList();
    }


    /**
     * 获取统计模块刷选条件部门列表
     */
    private void getStatisticsConditionDeptList() {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", MoccaPreferences.companyId.get());
        httpModel.getStatisticsConditionDeptList(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                StaticsDeptListEntity entity = null;
                if (model instanceof StaticsDeptListEntity) {
                    entity = (StaticsDeptListEntity) model;
                }
                if (entity != null && entity.getCode() == ConstantNetworkCode.SuccedCode && entity.getData() != null) {
                    for (int i = 0; i < entity.getData().size(); i++) {
                        supplierEntitiess.add(new StaticsSelectTypeEntity(entity.getData().get(i).getDepartmentName(), entity.getData().get(i).getId(), false));
                    }
                    if (supplierEntitiess.size() > 0) {
                        supplierEntitiess.get(0).setSelect(true);
                        adapter_type.addDataBottom(supplierEntitiess.get(0));
                        searchStatisicsData();
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
            }
        });
    }

    /**
     * 修改查询的数据类型
     */
    private void setSearchTypeStatus(int position) {
        tv_number.setTextColor(getResources().getColor(R.color.black));
        view_number.setVisibility(View.INVISIBLE);
        tv_money.setTextColor(getResources().getColor(R.color.black));
        view_money.setVisibility(View.INVISIBLE);
        switch (position) {
            case 0:
                tv_money.setTextColor(getResources().getColor(R.color.home_color));
                view_money.setVisibility(View.VISIBLE);
                type = "amount";
                break;
            case 1:
                tv_number.setTextColor(getResources().getColor(R.color.home_color));
                view_number.setVisibility(View.VISIBLE);
                type = "req";
                break;
        }
        searchStatisicsData();
    }

    /**
     * 起止日期的点击事件
     */
    private AdapterView.OnItemClickListener onItemClickListener_time = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            setTimeEntitiesStatus(i);
        }
    };

    /**
     * 修改起止日期的状态
     *
     * @param position
     */
    private void setTimeEntitiesStatus(int position) {
        for (int i = 0; i < adapter_time.getData().size(); i++) {
            adapter_time.getData().get(i).setSelect(false);
        }
        adapter_time.getData().get(position).setSelect(true);
        adapter_time.notifyDataSetChanged();
        dimension = data_dimension[position];
        searchStatisicsData();
    }

    /**
     * 显示选择框
     */
    private void showSelectTypePopup() {
        img_select.setImageResource(R.mipmap.back_gray_top_icon);
        view_backgroud.setVisibility(View.VISIBLE);
        View v1 = LayoutInflater.from(getActivity()).inflate(R.layout.popup_statics_select_supplier, null);// 创建view
        popupWindow = new PopupWindow(v1, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);// 实例化popupwindow的方法
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        // 这个方法是为了当点击除了popupwindow的其他区域可以关闭popupwindow的方法
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.style.popwin_anim_top_style);
        popupWindow.showAsDropDown(grid_type, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                img_select.setImageResource(R.mipmap.back_gray_botton_icon);
                view_backgroud.setVisibility(View.GONE);
            }
        });
        GridView grid_supplier = v1.findViewById(R.id.grid_popup_static_select_supplier);
        itemStaticSelectSupplierAdapter = new ItemStaticSelectSupplierAdapter(mContext);
        grid_supplier.setAdapter(itemStaticSelectSupplierAdapter);
        itemStaticSelectSupplierAdapter.addDataBottom(supplierEntitiess);
        grid_supplier.setOnItemClickListener(onItemClickListener_supplier);
        TextView tv_confirm = v1.findViewById(R.id.tv_popup_statics_supplier_confirm);
        tv_confirm.setOnClickListener(onClickListener);


    }


    /**
     * 选择供应商的列表的点击事件
     */
    private AdapterView.OnItemClickListener onItemClickListener_supplier = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            if (supplierEntitiess.get(position).isSelect() == false && getSelectTypeEntities().size() == 3) {
                ToastUtils.show_toast(HintConstants.STATICS_SELECT_SIZE);
                return;
            }
            supplierEntitiess.get(position).setSelect(!supplierEntitiess.get(position).isSelect());
            itemStaticSelectSupplierAdapter.setdate(supplierEntitiess);
        }
    };

    /**
     * 获取选中的选择的供应商数量
     *
     * @return
     */
    private List<StaticsSelectTypeEntity> getSelectTypeEntities() {
        List<StaticsSelectTypeEntity> selectTypeEntities = new ArrayList<>();
        for (int i = 0; i < supplierEntitiess.size(); i++) {
            if (supplierEntitiess.get(i).isSelect()) {
                selectTypeEntities.add(supplierEntitiess.get(i));
            }
        }
        return selectTypeEntities;
    }
}
